package multi_thread.master.tools;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAccumulator;

/**
 * @author Cheng Jun
 * Description: https://www.bbsmax.com/A/rV57qvqRzP/
 * LongAccumulator类的BUG
 * @version 1.0
 * @date 2022/5/20 17:33
 * @see LongAccumulator
 * 暂不做学习要求
 */
public class LongAccumulatorExample {
    //设置初始值为1查看输出结果
    private static volatile LongAccumulator count = new LongAccumulator((x, y) -> x + y, 1);
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            count.reset();
            averageTest();
        }
    }
    public static void averageTest() throws InterruptedException {
        long t1 = System.currentTimeMillis();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(50, 50, 60,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(5), new ThreadPoolExecutor.AbortPolicy());
        CountDownLatch latch = new CountDownLatch(50);
        for (int i = 0; i < 50; i++) {
            executor.execute(() -> {
                try {
                    for (int j = 0; j < 1000000; j++) {
                        count.accumulate(1);
                    }
                } finally {
                    latch.countDown();
                }
            });
        }
        latch.await();
        long t2 = System.currentTimeMillis();
        System.out.println(String.format("结果：%s,耗时(ms)：%s", count.longValue(), (t2 - t1)));
        executor.shutdown();
    }

}
